<?php
class TanTanXangaPlugin {
    function TanTanXangaPlugin() {
        add_action('admin_menu', array(&$this, 'addhooks'));
        add_action('activate_tantan/xanga-crosspost.php', array(&$this, 'activate'));
        //add_action('activate_tantan/xanga-crosspost.php', array(&$this, 'deactivate'));
        if ($_GET['tantanActivate'] == 'xanga-crosspost') {
            $this->showConfigNotice();
        }
    }
    
    function admin() {
        require_once(dirname(__FILE__).'/lib.xanga.php');
        $xanga = new TanTanXanga();
        if ($_POST['action'] == 'save') {
            update_option('tantan_xanga_options', $_POST['options']);
        } elseif ($_POST['action'] == 'login') {
            if ($xanga->login($_POST['user'], $_POST['password'])) {
                update_option('tantan_xanga_session', $xanga->getSession());
                update_option('tantan_xanga_user', $_POST['user']);
                $message = "Successfully link your Xanga account.";
            } else {
                $error = "Error: ".$xanga->getError();
            }
        } elseif ($_POST['action'] == 'logout') {
            update_option('tantan_xanga_session', '');
        }
        
        $session = get_option('tantan_xanga_session');
        $user    = get_option('tantan_xanga_user');
        $options = get_option('tantan_xanga_options');
        $categories = $this->_getCategories();
        
        $xanga->setOptions($options);
        include(dirname(__FILE__).'/admin-options.html');
    }
    function publish_post($post_id) {
        require_once(dirname(__FILE__).'/lib.xanga.php');
        $xanga = new TanTanXanga();
        $session = get_option('tantan_xanga_session');
        $user = get_option('tantan_xanga_user');
        if (!$session) {
            return $post_id;
        }
        $options = get_option('tantan_xanga_options');
        
        $xanga->setOptions($options);
        if (is_array($_POST['tantan_xanga_options']) && $_POST['tantan_xanga_options']['override']) {
            $xanga->setOptions(TanTanXangaPlugin::saveXangaPostOptions($post_id, $_POST['tantan_xanga_options']));
        } elseif ($xangaPostOptions = get_post_meta($post_id, 'xanga_options', true)) {
            $xanga->setOptions($xangaPostOptions);
        }
        
        if ($xanga->getOption('nocrosspost')) {
            return $post_id;
        }

		$cats = get_the_category($post_id);

        if (($options['publish_mode'] == 'restrict') && is_array($cats)) 
        foreach ($cats as $cat) {
            if (!$options['category'][$cat->cat_ID]) return $post_id;
            //if (!in_category($c)) {
            //    return $post_id;
            //}
        }
        
        
        $xanga->setSession($session, $user);
        $xanga_post_id = TanTanXangaPlugin::getXangaID($post_id);

        query_posts('p=' . $post_id);
		the_post();
		
		//if ($post->post_status == 'future') return $post_id;
		
		$content = get_the_content();
		$content = apply_filters('the_content', $content);
		$content = str_replace(']]>', ']]>', $content);
	 	$s = array('&acirc;&euro;&trade;' => '&rsquo;',         // Right-apostrophe (eg in I'm)
		  '&acirc;&euro;&oelig;' => '&ldquo;',                  // Opening speech mark
		  '&acirc;&euro;&ldquo;' => '&mdash;',                  // Long dash
		  '&acirc;&euro;' => '&rdquo;',                         // Closing speech mark
		  '&Atilde;&copy;' => '&eacute;',                       // e acute accent
		  chr(226) . chr(128) . chr(153) => '&rsquo;',          // Right-apostrophe again
		  chr(226) . chr(128) . chr(147) => '&mdash;',          // Long dash again
		  chr(226) . chr(128) . chr(156) => '&ldquo;',          // Opening speech mark
		  chr(226) . chr(128) . chr(148) => '&mdash;',          // M dash again
		  chr(226) . chr(128) . chr(133) => '&#8230',
		  '…' => '&#8230',
		  chr(226) . chr(128) => '&rdquo;',                     // Right speech mark
		  chr(195) . chr(169) => '&eacute;',                    // e acute again
		  );
		$content = str_replace(array_keys($s), array_values($s), $content);

		$cat_class = "tantan-entry ";
		if (is_array($cats)) foreach ($cats as $cat) {
		    $cat_class .= "$cat->category_nicename ";
		}
		$body = "<div class=\"$cat_class\">".
            "<h3><a href=\"".get_permalink()."\">".the_title('', '', false)."</a></h3>".
            $content;
		  
        $enclosure = get_post_meta($post_id, 'enclosure', true);
        if ($enclosure) { // hmm, this is kinda specific to tantannoodles...
            $mp3 = split("\n", $enclosure);
            if (!$mp3[2] || ($mp3[2] && ereg('audio',$mp3[2]))){
                $object = '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="200" height="25" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0" >'.
                    '<param name="movie" value="'.get_bloginfo('siteurl').'/wp-content/themes/tantan/mp3/mp3player.swf?config='.get_bloginfo('siteurl').'/wp-content/themes/tantan/mp3/config.xml&file='.
                        trim($mp3[0]).'" />' .
                    '<param name="wmode" value="transparent" />'.
                    '<embed src="'.get_bloginfo('siteurl').'/wp-content/themes/tantan/mp3/mp3player.swf?config='.get_bloginfo('siteurl').'/wp-content/themes/tantan/mp3/config.xml&file='.
                        trim($mp3[0]).'" wmode="transparent" width="200" height="25" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />'.
                    '</object>';
                $body .= $object;
            }
		}

		$body .= "<p class=\"tantan-comments\"><em><a href=\"" . get_permalink() ."#comments\">Leave / read comments</a></em></p>\n";
		
		$body .= '</div>';

		$post = array(
            'title' => get_the_title(),
            'body' => $body,
		);
        
        if ($xanga_post_id) {
            $xanga->editPost($xanga_post_id, $post);
        } else {
            if ($xanga_post_id = $xanga->createPost($post)) {
                TanTanXangaPlugin::setXangaID($post_id, $xanga_post_id);
            } else { // failed to create a xanga post
                echo 'hmm, error?';
            }
        }
    }
    function delete_post($post_id) {
        require_once(dirname(__FILE__).'/lib.xanga.php');
        $options = get_option('tantan_xanga_options');

        $xanga = new TanTanXanga();
        $xanga->setOptions($options);
        $session = get_option('tantan_xanga_session');
        $user = get_option('tantan_xanga_user');
        if (!$session) {
            return $post_id;
        }
        $xanga->setSession($session, $user);
        $xanga_post_id = TanTanXangaPlugin::getXangaID($post_id);
        if ($xanga_post_id) {
            $xanga->deletePost($xanga_post_id);
        }
    }
    function save_post($post_id) {
        if (is_array($_POST['tantan_xanga_options']) && $_POST['tantan_xanga_options']['override']) {
            TanTanXangaPlugin::saveXangaPostOptions($post_id, $_POST['tantan_xanga_options']);
        }
    }

    function dbx_page_sidebar_post() {
        global $post;
        $xangaOptions = get_option('tantan_xanga_options');
        $user = get_option('tantan_xanga_user');
        $xanga_id = TanTanXangaPlugin::getXangaID($post->ID);
        if ($post->ID) {
            $xangaPostOptions = get_post_meta($post->ID, 'xanga_options', true);
            if (is_array($xangaPostOptions)) {
                if (is_array($xangaOptions)) {
                    $xangaOptions = array_merge($xangaOptions, $xangaPostOptions);
                } else {
                    $xangaOptions = $xangaPostOptions;
                }
            }
        }
        include(dirname(__FILE__).'/admin-post-options.html');
    }
    function activate() {
        wp_redirect('plugins.php?activate=true&tantanActivate=xanga-crosspost');
        exit;
    }
    function deactivate() {}
    
    function showConfigNotice() {
        add_action('admin_notices', create_function('', 'echo \'<div id="message" class="updated fade"><p>Xanga Crosspost <strong>activated</strong>. <a href="options-general.php?page=tantan/xanga/class-admin.php">Configure the plugin &gt;</a></p></div>\';'));
    }
    function version_check() {
        global $TanTanVersionCheck;
        if (is_object($TanTanVersionCheck)) {
            $data = get_plugin_data(dirname(__FILE__).'/../xanga-crosspost.php');
            $TanTanVersionCheck->versionCheck(385, $data['Version']);
        }
    }
    function addhooks() {
        add_options_page('Xanga', 'Xanga Crosspost', 10, __FILE__, array(&$this, 'admin'));
        add_action('publish_post', array(&$this, 'publish_post'), 9);
        add_action('delete_post', array(&$this, 'delete_post'), 9);
        add_action('edit_post', array(&$this, 'save_post'), 9);
        add_action('dbx_post_sidebar', array(&$this, 'dbx_page_sidebar_post'));
        $this->version_check();
    }
    function saveXangaPostOptions($post_id, $options) {
        if (!$options['comments']) $options['comments'] = 'off';
        if (!update_post_meta($post_id, 'xanga_options', $options)) {
            add_post_meta($post_id, 'xanga_options', $options);
        }
        return $options;
    }
    function setXangaID($post_id, $xanga_id) {
        if (!update_post_meta($post_id, 'xanga_id', $xanga_id)) {
            add_post_meta($post_id, 'xanga_id', $xanga_id);
        }
    }
    function getXangaID($post_id) {
        return get_post_meta($post_id, 'xanga_id', true);
    }
    function _getCategories($parent='') {
		if (function_exists('get_terms')) {
        	$categories = get_categories('get=all');
			return $categories;		    
		} else {
	
		global $wpdb; 
    	$query = "
    		SELECT cat_ID, cat_name, category_nicename, category_parent
    		FROM $wpdb->categories 
    		WHERE cat_ID > 0 AND category_parent = '".addslashes($parent)."'
    	    ORDER BY cat_name 
    		";
    	$categories = $wpdb->get_results($query);
    	return $categories;
		}
    }
}
?>